//
//  StatusPictureView.m
//  王雷Sinoweibo
//
//  Created by wanglei on 16/11/24.
//  Copyright © 2016年 wanglei. All rights reserved.
//

#import "StatusPictureView.h"
#import "Masonry.h"
#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS
#import "UIlabel+extension.h"
#import "PictureCell.h"
#import "SDPhotoBrowser.h"

static NSString *PictureCellId = @"PictureCellId";

@interface StatusPictureView ()<UICollectionViewDelegate,UICollectionViewDataSource,SDPhotoBrowserDelegate>

@end

@implementation StatusPictureView

-(instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    
    CGFloat itemWidth = (ScreenWidth - StatusCellMargin * 2.0 - PictureCellMargin * 2.0)/3;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
    flowLayout.minimumLineSpacing = PictureCellMargin;
    flowLayout.minimumInteritemSpacing = PictureCellMargin;
    self.flowLayout = flowLayout;
    
    self = [super initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    self.backgroundColor = [UIColor lightGrayColor];
    [self registerClass:[PictureCell class] forCellWithReuseIdentifier:PictureCellId];
    self.dataSource = self;
    self.delegate = self;
    self.scrollsToTop = false;
    UILabel *label = [[UIlabel_extension alloc]initWithtext:nil fontsize:40 textColor:[UIColor redColor] Alignment:NSTextAlignmentCenter];
    _testLabel = label;
    _testLabel.hidden = YES;
    [self addSubview:_testLabel];
    [_testLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
    }];
    return self;
}

-(void)setImageURLs:(NSArray *)imageURLs{
    
    //    注意必须把赋值放到给pSize赋值的前面,这样self.imageURLs.count才能取到值
    _imageURLs = imageURLs;
    CGSize pSize = self.calclatePictureViewSize;
    NSValue *sizeValue = [NSValue valueWithCGSize:pSize];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(sizeValue);
    }];
#pragma mark:在下面注释的地方使用self.imageURLs 会取不到属性,而是直接跳到set方法里面了,很奇怪 ????
    //self.imageURLs = imageURLs;
    
    [self reloadData];
    self.testLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)_imageURLs.count];
    if (imageURLs == nil) {
        return;
    }
}

- (CGSize)calclatePictureViewSize{
    
    CGFloat itemWidth = (ScreenWidth - StatusCellMargin * 2.0 - PictureCellMargin * 2.0)/3;
    CGFloat width4 = itemWidth * 2 + PictureCellMargin;
    /*
     总高度暂时存疑
     图片数     行数            总宽度                         总高度??
     1,2,3   -> 1 -> 2itemWidth +1 PictureCellMargin  ->1itemWidth + 0PictureCellMargin
     4,5,6   -> 2 -> 3itemWidth +2 PictureCellMargin  ->2itemWidth + 1PictureCellMargin
     7,8,9   -> 3 -> 3itemWidth +2 PictureCellMargin  ->3itemWidth + 2PictureCellMargin
     */
    NSInteger imageCount = self.imageURLs.count;
    CGFloat rowCount = (imageCount - 1) / 3 + 1;
    CGFloat widthDefault = itemWidth * 3 + PictureCellMargin * 2;
    CGFloat heightDefault = (rowCount - 1) * PictureCellMargin + rowCount * itemWidth;
    CGSize imageSize = CGSizeMake(150, 200);
    //    547 × 648
    switch (imageCount) {
        case 0:
            return CGSizeZero;
            break;
        case 1:{
            //   确保StatusPictureView的大小是和图片的大小是一致的
            imageSize = CGSizeMake(100, 100);
            //1,需要根据图片的url 获取缓存中缓存的图片对象]
            //从磁盘中加载图片对象
            NSString *key = [self.imageURLs[0] absoluteString];
            UIImage *image = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:key];
            if (image != nil) {
                imageSize = image.size;
            }
            self.flowLayout.itemSize = imageSize;
            return imageSize;
        }
            break;
            
        case 4:{
            self.flowLayout.itemSize  = CGSizeMake(itemWidth, itemWidth);
            return CGSizeMake(width4, width4);
            break;
        }
        default:{
            self.flowLayout.itemSize  = CGSizeMake(itemWidth, itemWidth);
            return CGSizeMake(widthDefault,heightDefault);
            break;
        }
    }
}

//实现数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;{
    
    if (!self.imageURLs) {
        
        return 0;
    }
    return self.imageURLs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{
    
    PictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:PictureCellId forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[PictureCell alloc]initWithFrame:[UIScreen mainScreen].bounds];
    }
    
    //    cell.backgroundColor = indexPath.item % 2 == 0 ? [UIColor redColor] : [UIColor greenColor];
    cell.imageURL = self.imageURLs[indexPath.item];
    return cell;
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;{
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.sourceImagesContainerView = self;
    browser.imageCount = self.imageURLs.count;
    browser.currentImageIndex = indexPath.item;
    browser.delegate = self;
    [browser show]; // 展示图片浏览器
}

//SDPhotoBrowserDelegate代理方法的实现

// 注意点击保存照片时要早info.plist里面设置图片 http://blog.csdn.net/runintolove/article/details/52087623
/**
 返回临时占位图片
 */
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index;{
    // 获取indexPath
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath];
    PictureCell *picCell = (PictureCell *)cell;
    if (picCell != nil) {
        return picCell.iconView.image;
    }else{
        return nil;
    }
}

/**
 返回高质量的图片,最迟点击的是低质量的图片
 */
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index;{
    NSURL *url = self.imageURLs[index];
    NSString *urlString = url.absoluteString;
    NSString *str = [urlString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    NSURL *urls = [NSURL URLWithString:str];
    if (urls != nil) {
        return urls;
    }else{
        return nil;
    }
}




@end
